<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="入库单编号" prop="recptCode">
        <el-input
          v-model="queryParams.recptCode"
          placeholder="请输入入库单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入库单名称" prop="recptName">
        <el-input
          v-model="queryParams.recptName"
          placeholder="请输入入库单名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产工单" prop="workorderCode">
        <el-input
          v-model="queryParams.workorderCode"
          placeholder="请输入生产工单编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mes:wm:productrecpt:edit','mes:pro:productrecpt:edit']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:wm:productrecpt:edit','mes:pro:productrecpt:edit']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productrecptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库单编号" width="130px" align="center" prop="recptCode" >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleView(scope.row)">{{ scope.row.recptCode }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="入库单名称" width="150px" align="center" prop="recptName" :show-overflow-tooltip="true"/>
      <el-table-column label="生产工单编码" width="150px" align="center" prop="workorderCode" />
      <el-table-column label="产品编码" align="center" prop="itemCode" />
      <el-table-column label="产品名称" align="center" prop="itemName" />
      <el-table-column label="入库日期" align="center" prop="recptDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recptDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-video-play"
            v-if="scope.row.status =='PREPARE'"
            @click="handleExecute(scope.row)"
            v-hasPermi="['mes:wm:productrecpt:exec']"
          >执行入库</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status =='PREPARE'"
            v-hasPermi="['mes:wm:productrecpt:edit','mes:pro:productrecpt:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.status =='PREPARE'"
            v-hasPermi="['mes:wm:productrecpt:edit','mes:pro:productrecpt:edit']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改产品入库录对话框 -->
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="入库单编号" prop="recptCode">
              <el-input v-model="form.recptCode" :disabled='form.recptId?true:false' placeholder="请输入入库单编号" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item  label-width="80">
              <el-switch 
                :disabled="form.recptCode != null"
                v-model="autoGenFlag"
                active-color="#13ce66"
                active-text="自动生成"
                @change="handleAutoGenChange(autoGenFlag)" v-if="optType != 'view' && form.status =='PREPARE'">               
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库单名称" prop="recptName">
              <el-input v-model="form.recptName" placeholder="请输入入库单名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产工单" prop="workorderCode">
              <el-input v-model="form.workorderCode" placeholder="请选择生产工单" >
                <el-button slot="append" icon="el-icon-search" @click="handleWorkorderSelect"></el-button>
              </el-input>
              <WorkorderSelect ref="woSelect" v-if="showItemSelect" @closeSelect="closeSelect" @onSelected="onWorkorderSelected"></WorkorderSelect>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="生产工单名称" prop="workorderName">
              <el-input v-model="form.workorderName" readonly="readonly" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库日期" prop="recptDate">
              <el-date-picker clearable
                v-model="form.recptDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择入库日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>       
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider v-if="optType != 'view'" content-position="center">物料信息</el-divider> 
             <el-card shadow="always" v-if="optType != 'view'" class="box-card">
         <Productrecptline 
           ref="productrecptline"
           :recptId="form.recptId" 
           :optType="optType" 
           :workorderId="form.workorderId" 
           :itemId="form.itemId"
           @lineDataChanged="onLineDataChanged">
         </Productrecptline>
       </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel" v-if="optType =='view' || form.status !='PREPARE' ">返回</el-button>
        <el-button type="primary" @click="submitForm" v-if="form.status =='PREPARE' && optType !='view' ">保 存</el-button>        
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProductrecpt, getProductrecpt, delProductrecpt, addProductrecpt, updateProductrecpt ,execute} from "@/api/mes/wm/productrecpt";
import WorkorderSelect from "@/components/workorderSelect/single.vue"
import Productrecptline from "./line.vue"
import {getTreeList} from "@/api/mes/wm/warehouse"
import {genCode} from "@/api/system/autocode/rule"
import { listWorkorderbom } from "@/api/mes/pro/workorderbom"
export default {
  name: "Productrecpt",
  dicts: ['mes_order_status'],
  components:{WorkorderSelect,Productrecptline},
  data() {
    return {
      // 调试配置
      debug: {
        enabled: true, // 是否启用调试模式
        logApiRequests: true, // 是否记录API请求
        logApiResponses: true, // 是否记录API响应
        logValidationErrors: true, // 是否记录验证错误
        showDetailedErrors: true // 是否显示详细错误信息
      },
      // 入库单ID
      //自动生成编码
      autoGenFlag:false,
      optType: undefined,
      warehouseInfo:[],
      warehouseOptions:[],
      warehouseProps:{
        multiple: false,
        value: 'pId',
        label: 'pName',
      },
      // 防止重复提交
      submitting: false,
      // 新增：存储生产工单的BOM信息
      workorderBomInfo: null,
      workorderQuantity: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品入库录表格数据
      productrecptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        recptCode: null,
        recptName: null,
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        areaId: null,
        areaCode: null,
        areaName: null,
        recptDate: null,
        status: null,
      },
      productRecptLineLists:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        recptCode: [
          { required: true, message: "入库单编号不能为空", trigger: "blur" }
        ],
        recptDate: [
          { required: true, message: "请选择入库日期", trigger: "blur" }
        ],
        workorderCode: [
          { required: true, message: "请选择生产工单", trigger: "blur" }
        ],
      },
              showItemSelect: true, // 显示物料选择
        workorderProductInfo: null, // 新增：存储生产工单的产品信息
        // 存储物料明细数据
        lineData: {
          lineList: [],
          totalQuantity: 0,
          savedCount: 0,
          unsavedCount: 0
        },
      };
  },
  created() {
    this.getList();
    this.getWarehouseList();
    // 初始化当前用户信息
    this.initUserInfo();
  },
  methods: {
    // 初始化用户信息
    initUserInfo() {
      const userInfo = this.$store.state.user;
      if (userInfo) {
        this.form.createBy = userInfo.name;
        this.form.updateBy = userInfo.name;
        this.form.userId = userInfo.id;
      }
    },
    /** 查询产品入库录列表 */
    getList() {
      this.loading = true;
      listProductrecpt(this.queryParams).then(response => {
        this.productrecptList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getWarehouseList(){
      getTreeList().then( response =>{        
        this.warehouseOptions = response.data;
        this.warehouseOptions.map(w =>{
          w.children.map(l =>{
                  let lstr =JSON.stringify(l.children).replace(/locationId/g,'lId').replace(/areaId/g, 'pId').replace(/areaName/g,'pName');                  
                  l.children = JSON.parse(lstr);
          });
          let wstr = JSON.stringify(w.children).replace(/warehouseId/g,'wId').replace(/locationId/g, 'pId').replace(/locationName/g,'pName');  
          w.children =  JSON.parse(wstr); 

        });
        let ostr=JSON.stringify(this.warehouseOptions).replace(/warehouseId/g,'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      // 重置子组件的复选框选择状态
      this.resetChildCheckboxState();
    },
    
    reset() {
      this.form = {
        recptId: null,
        recptCode: null,
        recptName: null,
        workorderId: null,
        workorderCode: null,
        workorderName: null,
        warehouseId: null,
        warehouseCode: null,
        warehouseName: null,
        locationId: null,
        locationCode: null,
        locationName: null,
        itemId: null,
        itemCode: null,
        itemName: null,
        unitOfMeasure: null,
        clientCode: null,
        clientName: null,
        areaId: null,
        areaCode: 'string',
        areaName: null,
        recptDate: new Date(),
        status: "PREPARE",
        remark: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        params:{},
        searchValue:'mul',
        specification:null,
        userId:null,
      };
      
      // 清理入库行明细数据
      this.productRecptLineLists = [];
      this.lineData = {
        lineList: [],
        totalQuantity: 0,
        savedCount: 0,
        unsavedCount: 0
      };
      
      this.getAndPrintLineData()
      this.autoGenFlag = false;
      this.submitting = false; // 重置提交状态
      this.resetForm("form");
      this.workorderProductInfo = null; // 重置生产工单产品信息
      this.workorderBomInfo = null; // 重置BOM信息
      this.workorderQuantity = null; // 重置工单数量
      // 重置子组件的复选框选择状态
      this.resetChildCheckboxState();
    },
    // 智能数据清理和验证方法
    cleanAndValidateLineData(lineList) {
      if (!lineList || lineList.length === 0) {
        return [];
      }
      const cleanedList = [];
      const seenKeys = new Set();
      const seenItemCodes = new Set();
      let duplicateCount = 0;
      let invalidCount = 0;
      
      lineList.forEach((line, index) => {
        // 1. 基础数据验证
        if (!line.itemId || !line.itemCode || !line.quantityRecived || line.quantityRecived <= 0) {
          invalidCount++;
          console.warn(`第${index + 1}行数据无效，已跳过:`, line);
          return;
        }
        // 2. 创建唯一标识符（基于多个字段）
        const uniqueKey = `${line.itemId}_${line.itemCode}_${line.batchCode || 'NO_BATCH'}_${line.warehouseId || 'NO_WH'}`;
        
        // 3. 检查重复
        if (seenKeys.has(uniqueKey)) {
          duplicateCount++;
          return;
        }
        if (seenItemCodes.has(line.itemCode)) {
          return;
        }
        // 5. 数据标准化
        const cleanedLine = {
          ...line,
          lineId: line.lineId || null, // 确保新增记录lineId为null
          recptId: line.recptId || null,
          createTime: line.createTime || this.formatDateTime(new Date()),
          updateTime: line.updateTime || this.formatDateTime(new Date()),
          createBy: line.createBy || this.form.createBy || 'admin',
          updateBy: line.updateBy || this.form.updateBy || 'admin',
          // 确保数值字段为数字类型
          quantityRecived: Number(line.quantityRecived) || 0,
          quantityMax: Number(line.quantityMax) || Number(line.quantityRecived) || 0
        };
        
        seenKeys.add(uniqueKey);
        seenItemCodes.add(line.itemCode);
        cleanedList.push(cleanedLine);
      });
      
      // 6. 输出清理结果
      if (duplicateCount > 0 || invalidCount > 0) {
        // 清理数据测试在控制台输出结果
        // console.log(`数据清理完成: 原始${lineList.length}条，清理后${cleanedList.length}条，重复${duplicateCount}条，无效${invalidCount}条`);
      }
      
      return cleanedList;
    },
    
    // 清理重复数据（保留原有方法以兼容）
    cleanDuplicateData() {
      if (!this.productRecptLineLists || this.productRecptLineLists.length === 0) {
        return;
      }
      
      const cleanedList = this.cleanAndValidateLineData(this.productRecptLineLists);
      if (cleanedList.length !== this.productRecptLineLists.length) {
        // 静默处理，只在控制台输出，这里是来告诉一共清理了多少多少重复数据
        // console.log(`清理了 ${this.productRecptLineLists.length - cleanedList.length} 条重复/无效数据`);
        this.productRecptLineLists = cleanedList;
      }
    },
    
    // 显示数据清理确认对话框（已废弃，改为静默处理）
    showDataCleanConfirm(cleanedList, originalCount) {
      // 静默处理，自动使用清理后的数据
      this.productRecptLineLists = cleanedList;
      // console.log(`数据自动清理完成，从 ${originalCount} 条记录清理到 ${cleanedList.length} 条有效记录`);
      // 继续提交流程
      this.continueSubmitForm();
    },
    
    // 继续提交表单（数据清理确认后调用）
    continueSubmitForm() {
      // 重新构建提交数据
      const productRecpts = {
        recptCode: this.form.recptCode,
        recptName: this.form.recptName,
        workorderId: this.form.workorderId,
        workorderCode: this.form.workorderCode,
        workorderName: this.form.workorderName,
        itemId: this.form.itemId,
        itemCode: this.form.itemCode,
        itemName: this.form.itemName,
        unitOfMeasure: this.form.unitOfMeasure,
        clientCode: this.form.clientCode,
        clientName: this.form.clientName,
        warehouseId: this.form.warehouseId,
        warehouseCode: this.form.warehouseCode,
        warehouseName: this.form.warehouseName,
        locationId: this.form.locationId,
        locationCode: this.form.locationCode,
        locationName: this.form.locationName,
        areaId: this.form.areaId,
        areaCode: this.form.areaCode,
        areaName: this.form.areaName,
        recptDate: this.form.recptDate,
        status: this.form.status,
        remark: this.form.remark,
        specification: this.form.specification,
        userId: this.form.userId,
        createBy: this.form.createBy,
        createTime: this.formatDateTime(new Date()),
        updateBy: this.form.updateBy,
        updateTime: this.formatDateTime(new Date()),
        params: this.form.params || {},
        searchValue: this.form.searchValue || "",
        attr1: this.form.attr1,
        attr2: this.form.attr2,
        attr3: this.form.attr3,
        attr4: this.form.attr4
      };
      
      const subfrom = {
        productRecpt: productRecpts,
        productRecptLineList: this.productRecptLineLists
      };
      
      console.log('使用清理后数据提交:', subfrom);
      addProductrecpt(subfrom).then(response => {
        // 静默处理成功，不显示提示
        this.form.recptId = response.data;
        this.saveReceiptLines();
        this.open = false;
        this.getList();
        this.submitting = false;
      }).catch(error => {
        this.submitting = false;
        this.open=false;
        console.error('新增失败:', error);
        // 显示具体的错误信息
        if (this.debug.showDetailedErrors && error.response && error.response.data) {
          if (this.debug.logApiResponses) {
            console.error('详细错误信息:', {
              status: error.response.status,
              statusText: error.response.statusText,
              data: error.response.data,
              headers: error.response.headers
            });
          }
        }
      });
    },
    
    // 重置子组件的复选框选择状态
    resetChildCheckboxState() {
      try {
        // 通过ref调用子组件的方法重置复选框状态
        if (this.$refs.productrecptline) {
          this.$refs.productrecptline.resetCheckboxState();
        }
      } catch (error) {
        console.error('重置子组件复选框状态失败:', error);
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.recptId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.optType = "add";
      this.title = "添加产品入库单";
      // 新增时自动生成入库单编号，这是在我新增时
      this.autoGenFlag = true;
      this.handleAutoGenChange(true);
      // 确保子组件能正确识别新增模式并加载所有数据
      this.$nextTick(() => {
        // 通知子组件数据已更新
        if (this.$refs.productrecptline) {
          this.$refs.productrecptline.getList();
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const recptId = row.recptId || this.ids
      this.optType = "edit";
      getProductrecpt(recptId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改产品入库单";
        
        // 确保子组件能正确识别修改模式并加载关联数据
        this.$nextTick(() => {
          // 通知子组件数据已更新
          if (this.$refs.productrecptline) {
            this.$refs.productrecptline.getList();
          }
        });
      });
    },
    handleView(row) {
      this.reset();
      this.optType = "view";
      const recptId = row.recptId || this.ids
      getProductrecpt(recptId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "查看产品入库单";
      });
    },
    //执行入库
    handleExecute(row){
      const recptIds = row.recptId || this.ids;
      this.$modal.confirm('确认执行入库？').then(function() {
        return execute(recptIds)//执行入库
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("入库成功");
      }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form);
      // 防止重复提交
      if (this.submitting) {
        this.$message.warning('正在提交中，请勿重复操作');
        return;
      }
      
      // 在提交之前获取并打印物料明细数据
      this.getAndPrintLineData();
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 前端数据验证和清理
          if (this.productRecptLineLists && this.productRecptLineLists.length > 0) {
            // 1. 检查是否有重复的主键
            const lineIds = this.productRecptLineLists
              .filter(line => line.lineId)
              .map(line => line.lineId);
            const uniqueLineIds = [...new Set(lineIds)];
            // 
            if (lineIds.length !== uniqueLineIds.length) {
              console.warn('检测到重复的主键ID，请检查数据');
              // 静默处理，不阻止提交
            }
            // 2. 验证必填字段
            console.log(this.productRecptLineLists,'this.productRecptLineLists')
            const invalidLines = this.productRecptLineLists.filter(line => 
              !line.itemId || !line.itemCode || !line.quantityRecived || line.quantityRecived <= 0
            );
            
            if (invalidLines.length > 0) {
              console.warn(`发现 ${invalidLines.length} 条无效的入库明细数据，请检查必填字段`);
              // 静默处理，不阻止提交，这里是我所添加的数据
            }
            // 3. 前端数据去重和清理
            const cleanedList = this.cleanAndValidateLineData(this.productRecptLineLists);
            if (cleanedList.length !== this.productRecptLineLists.length) {
              // 静默处理，自动使用清理后的数据
              console.log(`数据自动清理完成，从 ${this.productRecptLineLists.length} 条记录清理到 ${cleanedList.length} 条有效记录`);
              this.productRecptLineLists = cleanedList;
            }
          }
          
          this.submitting = true; // 设置提交状态
          
          if (this.form.recptId != null) {
            // 修改操作 - 确保所有必要字段都有值
            const updateData = this.buildUpdateData();
            console.log('修改提交的数据:', updateData);
            
            // 验证数据完整性
            const validation = this.validateSubmitData(updateData);
            if (!validation.isValid) {
              this.$modal.msgError(`数据验证失败:\n${validation.errors.join('\n')}`);
              this.submitting = false;
              return;
            }
            console.log(updateData,'修改修改');
            updateProductrecpt(updateData).then(response => {
              this.$modal.msgSuccess("修改成功");
              // 保存入库行明细
              this.saveReceiptLines();
              this.open = false;
              this.getList();
              this.submitting = false; // 重置提交状态
            }).catch(error => {
              this.submitting = false; // 重置提交状态
              console.error('更新失败:', error);
              // 显示具体的错误信息
              if (this.debug.showDetailedErrors && error.response && error.response.data) {
                this.reset()
                const errorMsg = error.response.data.msg || error.response.data.message || '未知错误';
                const errorCode = error.response.status || '未知状态码';
                // this.$modal.msgError(`更新失败 (${errorCode}): ${errorMsg}`);
                
                // 记录详细的错误信息到控制台
                if (this.debug.logApiResponses) {
                  console.error('详细错误信息:', {
                    status: error.response.status,
                    statusText: error.response.statusText,
                    data: error.response.data,
                    headers: error.response.headers
                  });
                }
              } else {
                this.$modal.msgError('更新失败，请检查数据或联系管理员');
              }
              // 数据修改失败时也关闭弹窗
              this.open = false;
            });
          } else {
            // 新增操作 - 构建入库单数据，使用表单中的实际数据
            const productRecpts = this.buildAddData();
            
            // 验证数据完整性
            const validation = this.validateSubmitData(productRecpts);
            if (!validation.isValid) {
              this.$modal.msgError(`数据验证失败:\n${validation.errors.join('\n')}`);
              this.submitting = false;
              return;
            }
            
            // 确保入库行明细数据不包含重复的主键和无效数据
            const cleanLineList = this.productRecptLineLists
              .filter(line => line.itemId && line.itemCode && line.quantityRecived > 0) // 过滤无效数据
              .map(line => {
                // 如果是新增记录，确保lineId为null，并设置必要的默认值
                if (!line.lineId || line.lineId === '') {
                  return {
                    ...line,
                    lineId: null,
                    recptId: null, // 新增时设置为null
                    createTime: this.formatDateTime(new Date()),
                    updateTime: this.formatDateTime(new Date()),
                    createBy: this.form.createBy || 'admin',
                    updateBy: this.form.updateBy || 'admin'
                  };
                }
                return line;
              });
            
            // 智能去重逻辑：基于多个字段组合去重
            const uniqueLineList = [];
            const seenKeys = new Set();
            const duplicateCount = { total: 0, details: [] };
            cleanLineList.forEach((line, index) => {
              // 创建更精确的唯一标识符
              const key = `${line.itemId || ''}_${line.itemCode || ''}_${line.batchCode || 'NO_BATCH'}_${line.warehouseId || ''}`;
              
              if (!seenKeys.has(key)) {
                seenKeys.add(key);
                uniqueLineList.push(line);
              } else {
                duplicateCount.total++;
                duplicateCount.details.push({
                  index: index + 1,
                  itemCode: line.itemCode,
                  itemName: line.itemName,
                  batchCode: line.batchCode
                });
                console.warn('发现重复的物料记录，已跳过:', line);
              }
            });
            
            if (duplicateCount.total > 0) {
              const detailMsg = duplicateCount.details.map(d => 
                `第${d.index}行: ${d.itemCode}(${d.itemName}) - ${d.batchCode || '无批次号'}`
              ).join('\n');
              // 静默处理，只在控制台输出，不显示给用户，这是我在控制台测试的大厅输出
              // console.log(`检测到 ${duplicateCount.total} 条重复记录，已自动去重。重复详情:\n${detailMsg}`);
            }
            
            const subfrom = {
              productRecpt: productRecpts,
              productRecptLineList: uniqueLineList
            };
            // 这是我新增提交时的数据，是一个对象，里面有两个参数：productRecpt和productRecptLineList
            console.log('新增提交的数据:', subfrom);
            addProductrecpt(subfrom).then(response => {
              this.$modal.msgSuccess("新增成功");
              // 设置入库单ID
              this.form.recptId = response.data;
              // 保存入库行明细
              this.saveReceiptLines();
              this.open = false;
              this.getList();
              this.submitting = false; // 重置提交状态
            }).catch(error => {
              this.submitting = false; // 重置提交状态
              console.error('新增失败:', error);
              // 显示具体的错误信息
              if (this.debug.showDetailedErrors && error.response && error.response.data) {
                const errorMsg = error.response.data.msg || error.response.data.message || '未知错误';
                const errorCode = error.response.status || '未知状态码';
                // this.$modal.msgError(`新增失败 (${errorCode}): ${errorMsg}`);
                
                // 记录详细的错误信息到控制台
                if (this.debug.logApiResponses) {
                  console.error('详细错误信息:', {
                    status: error.response.status,
                    statusText: error.response.statusText,
                    data: error.response.data,
                    headers: error.response.headers
                  });
                }
              } else {
                this.open=false
                // this.$modal.msgError('新增失败，请检查数据或联系管理员');
              }
            });
          }
        }
      });
    },
    
    // 验证提交数据的完整性
    validateSubmitData(data) {
      const errors = [];
      
      // 检查必填字段
      const requiredFields = [
        { field: 'recptCode', name: '入库单编号' },
        { field: 'recptName', name: '入库单名称' },
        { field: 'workorderCode', name: '生产工单编码' },
        { field: 'itemCode', name: '产品编码' },
        { field: 'recptDate', name: '入库日期' }
      ];
      
      requiredFields.forEach(({ field, name }) => {
        if (!data[field] || data[field].toString().trim() === '') {
          errors.push(`${name}不能为空`);
        }
      });
      
      // 检查日期格式
      if (data.recptDate && !this.isValidDate(data.recptDate)) {
        errors.push('入库日期格式不正确');
      }
      
      // 检查数值字段
      if (data.workorderId && isNaN(Number(data.workorderId))) {
        errors.push('生产工单ID必须是数字');
      }
      
      if (data.itemId && isNaN(Number(data.itemId))) {
        errors.push('产品ID必须是数字');
      }
      
      // 检查入库行明细
      if (!this.productRecptLineLists || this.productRecptLineLists.length === 0) {
        errors.push('至少需要一条物料明细记录');
      } else {
        // 检查每条明细的必填字段
        this.productRecptLineLists.forEach((line, index) => {
          if (!line.itemId || !line.itemCode || !line.quantityRecived || line.quantityRecived <= 0) {
            errors.push(`第${index + 1}行物料明细数据不完整或数量无效`);
          }
        });
      }
      
      return {
        isValid: errors.length === 0,
        errors: errors
      };
    },
    
    // 检查日期是否有效
    isValidDate(date) {
      if (!date) return false;
      const d = new Date(date);
      return d instanceof Date && !isNaN(d);
    },
    
    // 格式化日期为 YYYY-MM-DD 格式
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      if (isNaN(d.getTime())) return '';
      
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    // 格式化日期时间为 YYYY-MM-DD HH:mm:ss 格式
    formatDateTime(date) {
      if (!date) return '';
      const d = new Date(date);
      if (isNaN(d.getTime())) return '';
      
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      const seconds = String(d.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    
    // 构建修改数据，确保所有必要字段都有值
    buildUpdateData() {
      const updateData = {
        ...this.form,
        // 确保时间字段有值
        updateTime: this.formatDateTime(new Date()),
        updateBy: this.form.updateBy || 'admin',
        // 确保状态字段有值
        status: this.form.status || 'PREPARE',
        // 确保必填字段不为null
        recptCode: this.form.recptCode || '',
        recptName: this.form.recptName || '',
        workorderCode: this.form.workorderCode || '',
        workorderName: this.form.workorderName || '',
        itemCode: this.form.itemCode || '',
        itemName: this.form.itemName || '',
        recptDate: this.form.recptDate || this.formatDate(new Date()),
        // 设置默认值避免null
        unitOfMeasure: this.form.unitOfMeasure || 'KG',
        specification: this.form.specification || '',
        remark: this.form.remark || '',
        // 确保对象字段不为null
        params: this.form.params || {},
        searchValue: this.form.searchValue || ""
      };
      
      // 过滤掉undefined值，保留null（因为某些字段可能允许为null）
      Object.keys(updateData).forEach(key => {
        if (updateData[key] === undefined) {
          updateData[key] = null;
        }
      });
      
      return updateData;
    },
    
    // 构建新增数据，确保所有必要字段都有值
    buildAddData() {
      const productRecpts = {
        recptCode: this.form.recptCode || 'string',
        recptName: this.form.recptName || 'string',
        workorderId: this.form.workorderId || 'string',
        workorderCode: this.form.workorderCode || 'string',
        workorderName: this.form.workorderName || 'string',
        itemId: this.form.itemId || 'string',
        itemCode: this.form.itemCode || 'string',
        itemName: this.form.itemName || 'string',
        unitOfMeasure: this.form.unitOfMeasure || 'KG',
        clientCode: this.form.clientCode || 'string',
        clientName: this.form.clientName || 'string',
        warehouseId: this.form.warehouseId || 'string',
        warehouseCode: this.form.warehouseCode || 'string',
        warehouseName: this.form.warehouseName || 'string',
        locationId: this.form.locationId || 'string',
        locationCode: this.form.locationCode || 'string',
        locationName: this.form.locationName || 'string',
        areaId: this.form.areaId || 123,
        areaCode: this.form.areaCode || 'areaCode',
        areaName: this.form.areaName || 'areaName',
        recptDate: this.form.recptDate || this.formatDate(new Date()),
        status: this.form.status || 'PREPARE',
        remark: this.form.remark || 'string',
        specification: this.form.specification || 'string',
        userId: this.form.userId || 'string',
        createBy: this.form.createBy || 'admin',
        createTime: this.formatDateTime(new Date()),
        updateBy: this.form.updateBy || 'admin',
        updateTime: this.formatDateTime(new Date()),
        params: this.form.params || {},
        searchValue: this.form.searchValue || "string",
        attr1: this.form.attr1 || 'string',
        attr2: this.form.attr2 || 'string',
        attr3: this.form.attr3 || 'string',
        attr4: this.form.attr4 || 'string'
      };
      
      // 过滤掉undefined值，保留null（因为某些字段可能允许为null）
      Object.keys(productRecpts).forEach(key => {
        if (productRecpts[key] === undefined) {
          productRecpts[key] = 'string';
        }
      });
      return productRecpts;
    },
    
    // 保存入库行明细
    saveReceiptLines() {
      if (this.$refs.productrecptline && this.form.recptId) {
        this.$nextTick(() => {
          try {
            // 如果有BOM信息，先创建入库行明细
            if (this.workorderBomInfo && this.workorderQuantity) {
              this.$refs.productrecptline.createLinesFromBom(this.workorderBomInfo, this.workorderQuantity);
              // 清空BOM信息
              this.workorderBomInfo = null;
              this.workorderQuantity = null;
            }
          } catch (error) {
            // 完全静默处理，不显示任何错误提示
            console.error('保存入库行明细失败:', error);
          }
        });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const recptIds = row.recptId || this.ids;
      this.$modal.confirm('是否确认删除产品入库单编号为"' + recptIds + '"的数据项？').then(function() {
        return delProductrecpt(recptIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/mes/wm/productrecpt/export', {
        ...this.queryParams
      }, `productrecpt_${new Date().getTime()}.xlsx`)
    },
    //选择生产工单
    handleWorkorderSelect(){
      this.$refs.woSelect.showFlag = true;
    },
    onWorkorderSelected(row){
      if(row != undefined && row != null){
        //debugger;
        this.form.workorderId = row.workorderId;
        this.form.workorderCode = row.workorderCode;
        this.form.workorderName = row.workorderName;
        this.form.itemId = row.productId;
        this.form.itemCode = row.productCode;
        this.form.itemName = row.productName;
        this.form.unitOfMeasure = row.unitOfMeasure;
        this.form.clientCode = row.clientCode;
        this.form.clientName = row.clientName;
        
        // 设置生产工单产品信息
        this.workorderProductInfo = {
          productCode: row.productCode,
          productName: row.productName,
          specification: row.productSpc,
          quantity: row.quantity,
          unitOfMeasure: row.unitOfMeasure
        };
        
        // 自动创建产品入库明细，将生产工单产品信息渲染到物料信息表格
        this.createProductInboundLine(row);
        
        // 获取生产工单BOM信息，自动创建入库行明细
        this.getWorkorderBomAndCreateLines(row.workorderId, row.quantity);
        this.closeSelect();
      }
    },
    
    // 自动创建产品入库明细
    createProductInboundLine(workorderData) {
      // 确保子组件已加载
      this.$nextTick(() => {
        if (this.$refs.productrecptline) {
          // 创建产品入库明细数据
          const productLine = {
            lineId: null,
            recptId: this.form.recptId,
            itemId: workorderData.productId,
            itemCode: workorderData.productCode,
            itemName: workorderData.productName,
            specification: workorderData.productSpc || '无',
            unitOfMeasure: workorderData.unitOfMeasure || 'PCS',
            quantityRecived: workorderData.quantity || 1,
            quantityMax: workorderData.quantity || 1,
            batchCode: this.generateBatchCode(),
            warehouseId: null,
            warehouseCode: null,
            warehouseName: null,
            locationId: null,
            locationCode: null,
            locationName: null,
            areaId: null,
            areaCode: null,
            areaName: null,
            remark: `生产工单产品: ${workorderData.workorderCode}`,
            attr1: null,
            attr2: null,
            attr3: null,
            attr4: null,
            createBy: this.form.createBy || 'admin',
            createTime: this.formatDateTime(new Date()),
            updateBy: this.form.updateBy || 'admin',
            updateTime: this.formatDateTime(new Date())
          };
          
          // 调用子组件方法添加产品入库明细
          this.$refs.productrecptline.addProductLine(productLine);
          
          console.log('已自动创建产品入库明细:', productLine);
        }
      });
    },
    
    // 生成批次号
    generateBatchCode() {
      const now = new Date();
      const timestamp = now.getTime();
      const random = Math.floor(Math.random() * 1000);
      return `B${timestamp}${random}`;
    },
    
    // 获取生产工单BOM信息并创建入库行明细
    async getWorkorderBomAndCreateLines(workorderId, workorderQuantity) {
      try {
        // 获取生产工单的BOM信息
        const response = await listWorkorderbom({ workorderId: workorderId });
        if (response.rows && response.rows.length > 0) {
          // 存储BOM信息和工单数量，等入库单保存后再创建明细
          this.workorderBomInfo = response.rows;
          this.workorderQuantity = workorderQuantity;
          // 静默处理，不显示提示信息
          console.log(`已获取生产工单BOM信息，共 ${response.rows.length} 个物料`);
        }
      } catch (error) {
        console.error('获取生产工单BOM信息失败:', error);
        // 静默处理错误，不显示错误提示
      }
    },
    
    // 监听子组件数据变化事件
    onLineDataChanged(data) {
      
      this.lineData = data;
    },
    
    // 获取并打印子组件的物料明细数据
    getAndPrintLineData() {
      if (this.$refs.productrecptline) {
        // 获取子组件的物料明细列表
        const lineData = this.$refs.productrecptline.productrecptlineList;
        this.productRecptLineLists=lineData
        console.log( this.productRecptLineLists,'333')
      } else {
        // 尝试延迟获取
        setTimeout(() => {
          if (this.$refs.productrecptline) {
            this.getAndPrintLineData();
          } else {
            console.error('延迟后仍然无法获取子组件引用');
          }
        }, 100);
      }
    },
    
    //选择默认的仓库、库区、库位
    handleWarehouseChanged(obj){      
      if(obj !=null){
        this.form.warehouseId = obj[0];
        this.form.locationId = obj[1];
        this.form.areaId = obj[2];
      }
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag){
      if(autoGenFlag){
        genCode('PRODUCTRECPT_CODE').then(response =>{
          this.form.recptCode = response;
        });
      }else{
        this.form.recptCode = null;
      }
    },
    closeSelect(){
      this.showItemSelect = false;
      setTimeout(()=>{
        this.showItemSelect = true;
      }, 200)
    },
    
    // 格式化日期时间为后端期望的格式
    formatDateTime(date) {
      if (!date) return null;
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      const seconds = String(d.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }
  }
};
</script>

<style scoped>
.product-info-card {
  margin-bottom: 20px;
  border: 2px solid #e6f7ff;
  background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
}

.product-info-card .el-card__header {
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  color: white;
  padding: 12px 20px;
  border-bottom: none;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
}

.card-title i {
  margin-right: 8px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 6px;
  border: 1px solid #d9f2ff;
}

.info-label {
  font-weight: 600;
  color: #1890ff;
  margin-right: 8px;
  min-width: 80px;
}

.info-value {
  color: #262626;
  font-weight: 500;
}

.info-tip {
  margin-top: 16px;
  padding: 12px 16px;
  background: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 6px;
  color: #d46b08;
  display: flex;
  align-items: center;
}

.info-tip i {
  margin-right: 8px;
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .info-label {
    margin-bottom: 4px;
  }
}
</style>
